﻿using System;
using System.Collections.Specialized;
using System.Linq;
using StockAnalyst2.Plugins.Engine;
using Utils.Wpf;

namespace StockAnalyst2.Plugins
{
	internal class PluginSystemVM : ViewModelBase, IDisposable
	{
		#region Attributes

		private readonly PluginSystem _model;

		#endregion

		#region Properties

		public bool AreRealtimePluginsLoaded
		{
			get
			{
				return _model.Plugins.Any(p => p.SupportsRealtime);
			}
		}

		public bool AreHistoricalPluginsLoaded
		{
			get
			{
				return _model.Plugins.Count > 0;
			}
		}

		#endregion

		#region Public Methods

		public PluginSystemVM(PluginSystem model)
		{
			_model = model;
			_model.Plugins.CollectionChanged += this.Plugins_CollectionChanged; // Disposed
		}

		#endregion

		#region Event Handlers

		private void Plugins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			this.OnPropertyChanged("ArePluginsLoaded");
		}

		#endregion

		#region IDisposable

		protected bool Disposed { get; private set; }

		private void Dispose(bool disposing)
		{
			if (!this.Disposed)
			{
				this.InternalDispose(disposing);
			}

			this.Disposed = true;
		}

		protected virtual void InternalDispose(bool disposing)
		{
			if (disposing)
			{
				_model.Plugins.CollectionChanged -= this.Plugins_CollectionChanged;
			}

			// Dispose here only unmanaged objects 
			// Don’t use managed objects here because maybe 
			// they have been finalized already
		}

		public void Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		~PluginSystemVM()
		{
			this.Dispose(false);
		}

		#endregion

	}
}
